package com.xoa.controller.crm;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.crm.CustomerMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.crm.CrmContract;
import com.xoa.model.crm.Customer;
import com.xoa.model.crm.CustomerExample;
import com.xoa.model.users.Users;
import com.xoa.service.crm.CrmContractService;
import com.xoa.util.*;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhanglijun on 2019/5/30.
 */
@Controller
@RequestMapping("/crmContract")
public class CrmContractController {

    @Autowired
    private CrmContractService crmContractService;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @RequestMapping("/index")
    public String deptListShow() {
        return "app/crm/contract/contractIndex";
    }

    @RequestMapping("/addContract")
    public String addContract(){
        return "app/crm/contract/addContract";
    }
    @RequestMapping("/detailsContract")
    public String detailsContract(){
        return "app/crm/contract/detailsContract";
    }
    @RequestMapping("/updateContract")
    public String updateContract(){
        return "app/crm/contract/updateContract";
    }

    //处理时间  将前台传过来的时间存到数据库中
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    /**
     * 张丽军
     * 2019.5.30
     * 添加客户合同
     * @param request
     * @param crmContract
     * @return
     */
    @ResponseBody
    @RequestMapping("/addCrmContract")
    public BaseWrapper  addCrmContract(HttpServletRequest request, CrmContract crmContract){
        BaseWrapper baseWrapper=new BaseWrapper();
        crmContract.setCreateTime(new Date());
        crmContractService.addCrmContract(request,crmContract);
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("成功");
        baseWrapper.setStatus(true);
        return baseWrapper;
    }


    /**
     * 张丽军
     * 2019.5.30
     * 编辑客户合同
     * @param request
     * @param crmContract
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateCrmContract")
    public BaseWrapper  updateCrmContract(HttpServletRequest request, CrmContract crmContract){
        BaseWrapper baseWrapper=new BaseWrapper();
        crmContract.setUpdateTime(new Date());
        crmContractService.updateCrmContract(request,crmContract);
        baseWrapper.setFlag(true);
        baseWrapper.setMsg("成功");
        baseWrapper.setStatus(true);
        return baseWrapper;
    }

    /**
     * 张丽军
     * 2019.5.30
     * 查询客户合同列表
     * @param request
     * @param crmContract
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectCrmContract")
    public BaseWrappers selectCrmContract(HttpServletRequest request, HttpServletResponse response, CrmContract crmContract, String flag,Integer page,Integer pageSize,boolean useFlag){
        BaseWrappers baseWrapper=new BaseWrappers();

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("obj", crmContract);

        String totalMin=request.getParameter("totalMin");
        String totalMax=request.getParameter("totalMax");
        map.put("totalMin",totalMin);
        map.put("totalMax",totalMax);
        List<CrmContract> list = crmContractService.selectCrmContract(request,map,page,pageSize,useFlag);
        if(flag.equals("1")){
            for (CrmContract crmContract1:list){
                String typeString = null;
                String typeNum = crmContract1.getType();
                if (typeNum != null) {
                    switch (typeNum){
                        case "01":
                            typeString = "产品销售";
                            break;
                        case "02":
                            typeString = "服务";
                            break;
                        case "03":
                            typeString = "合作";
                            break;
                        case "04":
                            typeString = "代理";
                            break;
                        case "05":
                            typeString = "其他";
                            break;
                    }
                }
                crmContract1.setType(typeString);

                Byte stutus = crmContract1.getStatus();
                String byt = null;
                if(stutus != null){
                    switch (stutus){
                        case 0:
                            byt = "执行中";
                            break;
                        case 1:
                            byt = "结束";
                            break;
                        case 2:
                            byt = "意外终止";
                            break;
                    }
                }

                crmContract.setStatus(Byte.valueOf(byt));

                String pay = crmContract1.getPayWay();
                String payWay = "";
                if(pay!=null){
                    switch (pay){
                        case "01":
                            payWay = "现金";
                            break;
                        case "02":
                            payWay = "转账";
                            break;
                        case "03":
                            payWay = "支票";
                            break;
                        case "04":
                            payWay = "支付宝";
                            break;
                        case "05":
                            payWay = "微信";
                            break;
                        case "06":
                            payWay = "其他";
                            break;
                    }
                }
                crmContract.setPayWay(payWay);

                Byte remind = crmContract1.getRemindExpire();
                String bytr = null;
                if(remind!=null){
                    switch (remind){
                        case 0:
                            bytr = "否";
                            break;
                        case 1:
                            bytr = "是";
                            break;
                    }
                }
                crmContract.setRemindExpire(Byte.valueOf(bytr));

                Byte remindSms = crmContract1.getRemindRecieveSms();
                String bytSms = null;
                switch (remindSms){
                    case 0:
                        bytSms = "否";
                        break;
                    case 1:
                        bytSms = "是";
                        break;
                }
                crmContract.setRemindExpireSms(Byte.valueOf(bytSms));

                Byte appr = crmContract1.getApprovalStatus();
                String bytApp = null;
                switch (appr){
                    case 0:
                        bytApp = "待审批";
                        break;
                    case 1:
                        bytApp = "已通过";
                        break;
                    case 2:
                        bytApp = "已驳回";
                        break;
                }
                crmContract.setApprovalStatus(Byte.valueOf(bytApp));

            }
            String[] secondTitles = {"合同编号","合同名称","所属客户","合同类型","合同状态","总金额","总金额大写","已收款","支付方式","开始时间","结束时间","合同有效期","到期事务提醒","到期短信提醒","收款时间","交付时间","收款事务提醒","收款短信提醒","交付事务提醒","交付短信提醒","合同内容","甲方签约时间","甲方","乙方签约时间","乙方","项目","审批状态","审批人","审批时间","审批意见","备注","创建人","创建时间"};
            String[] beanProperty = {"contractNo","contractName","customerId","type","status","total","totalCaps","receivedMoney","payWay","startTime","endTime","validTime","remindExpire","remindExpireSms","recieveTime","deliverTime","remindRecieve","remindRecieveSms","remindDeliver","remindDeliverSms","content","fistPartySignTime","fistParty","secondPartySignTime","secondParty","item","approvalStatus","approvalUser","approvalTime","approvalAdvice","remark","creator","createTime"};
            ExcelUtils.exportExcel("销售合同表",secondTitles,beanProperty,list,response);


            baseWrapper.setFlag(true);
            baseWrapper.setMsg("导出成功");
            baseWrapper.setStatus(true);
        }else {
            PageParams params = (PageParams)map.get("page");
            baseWrapper.setTotal(params.getTotal());
            baseWrapper.setFlag(true);
            baseWrapper.setDatas(list);
            baseWrapper.setMsg("成功");
            baseWrapper.setStatus(true);
        }
        return baseWrapper;
    }


    /**
     * 张丽军
     * 2019.5.30
     * 查询客户合同详情
     * @param request
     * @param contractId
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectCrmContractById")
    public BaseWrapper selectCrmContractById(HttpServletRequest request, Integer contractId){
        BaseWrapper baseWrapper=new BaseWrapper();
        CrmContract crmContract = crmContractService.selectCrmContractById(request,contractId);
        baseWrapper.setFlag(true);
        baseWrapper.setData(crmContract);
        baseWrapper.setMsg("成功");
        baseWrapper.setStatus(true);
        return baseWrapper;
    }


    /**
     * 张丽军
     * 2019.5.30
     * 删除客户合同信息(伪删除1删除0未删除)
     * @param request
     * @param contractId
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteCrmContractById")
    public BaseWrapper deleteCrmContractById(HttpServletRequest request, Integer contractId){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        BaseWrapper baseWrapper=new BaseWrapper();
        CrmContract crmContract = crmContractService.selectCrmContractById(request,contractId);
        Date date = new Date();
        crmContract.setDeleteTime(date);
        crmContract.setDeleteUser(users.getUserId());
        crmContract.setIsDeleted((byte) 1);
        int a = crmContractService.updateDeleteStutus(request,crmContract);
        if(a>0){
            baseWrapper.setFlag(true);
            baseWrapper.setMsg("成功");
            baseWrapper.setStatus(true);
        }else {
            baseWrapper.setFlag(false);
            baseWrapper.setMsg("失败");
            baseWrapper.setStatus(false);
        }
        return baseWrapper;
    }

    /**
     * 张丽军
     * 2019.5.30
     * 导入功能
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/importFile")
    public ToJson importFile(MultipartFile file, HttpServletRequest request){
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        ToJson json = new ToJson(1,"error");
        try {
            String fileName = null;
            if (file != null) {
                fileName = file.getOriginalFilename();
            }
            if (fileName != null && (fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
                int count = 0;
                int flag = 0;
                Integer uId = (Integer)request.getSession().getAttribute("uid");
                List<CrmContract> list = new ArrayList<>();

                ExcelRead excelRead = new ExcelRead();
                List<Map<String, Object>> readList = excelRead.readExcel(file);
                for (Map<String, Object> map : readList) {
                    if (!"".equals(map.get("合同编号")) && !"".equals(map.get("合同编号"))) {
                        CrmContract crmContract = new CrmContract();

                        crmContract.setContractNo(map.get("合同编号").toString());
                        crmContract.setContractName(map.get("合同名称").toString());
                        crmContract.setCustomerId(Integer.valueOf(map.get("所属客户").toString()));
                        String typeStutus = map.get("合同类型").toString();
                        String b = "";
                        switch (typeStutus){
                            case "产品销售":
                                b = "01";
                                break;
                            case "服务":
                                b = "02";
                                break;
                            case "合作":
                                b = "03";
                                break;
                            case "代理":
                                b = "04";
                                break;
                            case "其他":
                                b = "05";
                                break;
                        }
                        crmContract.setType(b);

                        String stutus = map.get("合同状态").toString();
                        Byte byt = null;
                        switch (stutus){
                            case "执行中":
                                byt = 0;
                                break;
                            case "结束":
                                byt = 1;
                                break;
                            case "意外终止":
                                byt = 2;
                                break;
                        }
                        crmContract.setStatus(byt);

                        crmContract.setTotal(Long.valueOf(map.get("总金额").toString()));
                        crmContract.setTotalCaps(map.get("总金额大写").toString());
                        crmContract.setReceivedMoney(Long.valueOf(map.get("已收款").toString()));

                        String pay = map.get("支付方式").toString();
                        String payWay = "";
                        switch (pay){
                            case "现金":
                                payWay = "01";
                                break;
                            case "转账":
                                payWay = "02";
                                break;
                            case "支票":
                                payWay = "03";
                                break;
                            case "支付宝":
                                payWay = "04";
                                break;
                            case "微信":
                                payWay = "05";
                                break;
                            case "其他":
                                payWay = "06";
                                break;
                        }
                        crmContract.setPayWay(payWay);
                        crmContract.setStartTime(DateFormat.DateToStr(map.get("开始时间").toString()));
                        crmContract.setEndTime(DateFormat.DateToStr(map.get("结束时间").toString()));
                        crmContract.setValidTime(DateFormat.DateToStr(map.get("合同有效期").toString()));

                        String remind = map.get("到期事务提醒").toString();
                        Byte bytr = null;
                        switch (remind){
                            case "否":
                                bytr = 0;
                                break;
                            case "是":
                                bytr = 1;
                                break;
                        }
                        crmContract.setRemindExpire(bytr);

                        String remindSms = map.get("到期短信提醒").toString();
                        Byte bytSms = null;
                        switch (remindSms){
                            case "否":
                                bytSms = 0;
                                break;
                            case "是":
                                bytSms = 1;
                                break;
                        }
                        crmContract.setRemindExpireSms(bytSms);

                        crmContract.setRecieveTime(DateFormat.DateToStr(map.get("收款时间").toString()));
                        crmContract.setDeliverTime(DateFormat.DateToStr(map.get("交付时间").toString()));
                        crmContract.setRemindRecieve(Byte.valueOf(map.get("收款事务提醒").toString()));
                        crmContract.setRemindRecieveSms(Byte.valueOf(map.get("收款短信提醒").toString()));
                        crmContract.setRemindDeliver(Byte.valueOf(map.get("交付事务提醒").toString()));
                        crmContract.setRemindRecieveSms(Byte.valueOf(map.get("交付短信提醒").toString()));
                        crmContract.setContent(map.get("合同内容").toString());
                        crmContract.setFistPartySignTime(DateFormat.DateToStr(map.get("甲方签约时间").toString()));
                        crmContract.setFistParty(map.get("甲方").toString());
                        crmContract.setSecondPartySignTime(DateFormat.DateToStr(map.get("乙方签约时间").toString()));
                        crmContract.setSecondParty(map.get("乙方").toString());
                        crmContract.setItem(map.get("项目").toString());

                        String appr = map.get("审批状态").toString();
                        Byte bytApp = null;
                        switch (appr){
                            case "待审批":
                                bytApp = 0;
                                break;
                            case "已通过":
                                bytApp = 1;
                                break;
                            case "已驳回":
                                bytApp = 2;
                                break;
                        }
                        crmContract.setApprovalStatus(bytApp);
                        crmContract.setApprovalUser(map.get("审批人").toString());
                        crmContract.setApprovalTime(DateFormat.DateToStr(map.get("审批时间").toString()));
                        crmContract.setApprovalAdvice(map.get("审批意见").toString());
                        crmContract.setRemark(map.get("备注").toString());
                        crmContract.setCreator(users.getUserId());
                        crmContract.setCreateTime(new Date());

                        list.add(crmContract);
                        count++;
                    }
                }

                if (count > 0) {
                    flag = crmContractService.insertAll(list);
                }

                if (flag > 0){
                    json.setFlag(0);
                    json.setMsg("导入成功");
                    json.setTotleNum(count);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
    /**
     *查询付款方式
     */
    @RequestMapping("selectByPayment")
    @ResponseBody
    public ToJson<Integer> selectBySource(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            // List<CustomerWithBLOBs> data = customerService.selectBySource();
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("PAYMENTMETHOD");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }


    /**
     *合同类型
     */
    @RequestMapping("selectByContract")
    @ResponseBody
    public ToJson<Integer> selectByContract(HttpServletRequest request){
        ToJson json =new ToJson<Integer>(1,"err");
        try {
            // List<CustomerWithBLOBs> data = customerService.selectBySource();
            List<SysCode> sysCodes=sysCodeMapper.getSysCode("HR_STAFF_CONTRACT2");
            if(sysCodes!=null){
                json.setObj(sysCodes);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

    //客户查询
    @RequestMapping("/selectByConditionCust")
    @ResponseBody
    public ToJson<Customer>  selectByConditionCust(){
        ToJson<Customer> json = new ToJson<>(1,"err");
        try {

            CustomerExample customerExample = new CustomerExample();
            customerExample.createCriteria().andIsDeletedEqualTo((byte) 0);
            List<Customer> customers = customerMapper.selectByExample(customerExample);

            if(customers!=null){
                json.setObj(customers);
                json.setFlag(0);
                json.setMsg("true");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return json;
    }

}
